<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams">
        <el-form-item label="考试名称" prop="keywords">
          <el-select v-model="queryParams.active" class="!w-[100px]" filterable>
            <el-option
              v-for="(item, index) in activeOptions"
              :key="index"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="考生姓名" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="考生姓名"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="视频状态" prop="keywords">
          <el-select
            v-model="queryParams.status"
            placeholder="视频状态"
            clearable
            @keyup.enter="handleQuery"
          >
            <el-option :value="1" label="未上传" />
            <el-option :value="2" label="已上传" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            class="filter-item"
            type="primary"
            @click="handleQuery(false)"
          >
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card class="table-container" shadow="never">
      <template #header>
        <div class="flex-x-between">
          <div>
            <!--            <el-button-->
            <!--              v-hasPerm="['exam:exam:add']"-->
            <!--              type="success"-->
            <!--              @click="handleOpenDialog(undefined)"-->
            <!--            >-->
            <!--              <i-ep-plus />-->
            <!--              新增-->
            <!--            </el-button>-->
            <el-button
              v-hasPerm="['exam:exam:delete']"
              :disabled="ids.length === 0"
              type="danger"
              @click="handleDelete()"
            >
              <i-ep-delete />
              删除
            </el-button>
          </div>
          <div>
            <el-button
              v-hasPerm="['exam:exam:import']"
              type="default"
              @click="handleOpenImportant()"
            >
              <i-ep-upload />
              导入
            </el-button>
            <el-button
              v-hasPerm="['exam:exam:export']"
              type="default"
              @click="handleOpenExport()"
            >
              <i-ep-download />
              导出
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :center="true"
        :data="ExamList"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column
          label="考生姓名"
          max-width="100"
          min-width="100"
          prop="name"
          show-overflow-tooltip
        />
        <el-table-column label="联系人" min-width="100" prop="contact_person" />
        <el-table-column label="联系电话" min-width="120" prop="phone" />
        <el-table-column label="类型" min-width="100" prop="type">
          <template #default="scope">
            <el-tag v-if="scope.row.type == 1" type="success">朗诵</el-tag>
            <el-tag v-else type="danger">主持</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="级别" min-width="100" prop="type">
          <template #default="scope">{{ scope.row.level }}级</template>
        </el-table-column>
        <el-table-column label="查看视频" min-width="100" prop="video_status">
          <template #default="scope">
            <el-button
              type="primary"
              @click="previewVideo(scope.row)"
              :disabled="scope.row.status == 1"
            >
              查看视频
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="160" prop="createTime" />
        <el-table-column label="状态" min-width="100" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="primary">已报名</el-tag>
            <el-tag v-if="scope.row.status == 2" type="warning">已交卷</el-tag>
            <el-tag v-if="scope.row.status == 3" type="success">已阅卷</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="200">
          <template #default="scope">
            <!--            <el-button-->
            <!--              v-hasPerm="['exam:exam:edit']"-->
            <!--              :disabled="scope.row.status == 3"-->
            <!--              link-->
            <!--              size="small"-->
            <!--              type="primary"-->
            <!--              @click.stop="handleOpenDialog(scope.row.parentId, scope.row.id)"-->
            <!--            >-->
            <!--              <i-ep-edit />-->
            <!--              编辑-->
            <!--            </el-button>-->
            <el-button
              v-hasPerm="['exam:exam:upload']"
              link
              size="small"
              type="primary"
              @click.stop="handleOpenUpload(scope.row.id)"
            >
              <i-ep-upload />
              上传视频
            </el-button>
            <el-button
              v-hasPerm="['exam:exam:download']"
              link
              size="small"
              type="primary"
              @click.stop="downloadVideo(scope.row)"
            >
              <i-ep-download />
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        v-model:total="total"
        @pagination="handleQuery(false)"
      />
    </el-card>

    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      size="500px"
      @closed="handleCloseDialog"
    >
      <el-form
        ref="institutionFormRef"
        :model="formData"
        :rules="rules"
        label-position="top"
        label-width="80px"
      >
        <el-form-item label="所属上级" prop="parent_id">
          <el-tree-select
            v-model="formData.parent_id"
            :data="parentOptions"
            :render-after-expand="false"
            check-strictly
            filterable
            placeholder="选择所属上级"
          />
        </el-form-item>
        <el-form-item label="机构名称" prop="name">
          <template #label>
            <span>机构名称</span>
            <span class="form-label-extra">
              (连锁机构请在机构名称后注明XX分机构)
            </span>
          </template>
          <el-input
            v-model="formData.name"
            maxlength="30"
            placeholder="请输入机构名称"
          />
        </el-form-item>
        <el-form-item label="联系人" prop="person">
          <el-input v-model="formData.person" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="formData.phone"
            :disabled="formData.id != undefined"
            maxlength="11"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="所在地区" prop="area">
          <AreaCascader v-model="formData.area" @update:model-value="setArea" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入详细地址" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入联系邮箱地址" />
        </el-form-item>
        <el-form-item label="机构状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">冻结</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="机构类型">
          <el-radio-group v-model="formData.type">
            <el-radio :label="1">普通机构</el-radio>
            <el-radio :label="2">省承办</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
    <upload-video v-model:visible="showUpload" v-model:answer="answer_id" />
  </div>
</template>

<script lang="ts" setup>
import AreaAPI from "@/api/area";
import ActiveApi from "@/api/active";
import ExamAPI, { ExamForm, ExamQuery, ExamVO } from "@/api/exam";
import Upload from "@/views/demo/upload.vue";
import UploadVideo from "@/views/exam/components/upload-video.vue";

defineOptions({
  name: "Exam",
  inheritAttrs: false,
});

const activeOptions = ref([]);
const parentOptions = ref([]);
const areaOptions = reactive({
  province: [],
  city: [],
  districts: [],
});
const queryFormRef = ref(ElForm);
const institutionFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const dialog = reactive({
  title: "",
  visible: false,
});
const showUpload = ref(false);
const answer_id = ref(0);
const total = ref(0);
const queryParams = reactive<ExamQuery>({
  active: undefined,
  pageNum: 1,
  pageSize: 10,
});
const ExamList = ref<ExamVO[]>();
const importDialogVisible = ref(false);
const formData = reactive<ExamForm>({
  id: undefined,
  type: 1,
  area: [],
  status: 1,
});
const license = ref(["https://s2.loli.net/2023/05/24/yNsxFC8rLHMZQcK.jpg"]);
const rules = reactive({
  parent_id: [
    {
      required: true,
      message: "所属上级不能为空",
      trigger: "change",
    },
  ],
  name: [
    {
      required: true,
      message: "机构名称不能为空",
      trigger: "blur",
    },
  ],
  area: [
    {
      required: true,
      message: "所在地区不能为空",
      trigger: "blur",
    },
  ],
  address: [
    {
      required: true,
      message: "详细地址不能为空",
      trigger: "blur",
    },
  ],
  person: [
    {
      required: true,
      message: "联系人不能为空",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: "联系电话不能为空",
      trigger: "blur",
    },
  ],
});

/** 查询机构 */
async function handleQuery(isInit = false) {
  loading.value = true;
  if (isInit) {
    activeOptions.value = await ActiveApi.getOptions();
    queryParams.active = activeOptions.value[0]["value"];
  }
  ExamAPI.getList(queryParams).then((data) => {
    ExamList.value = data["list"];
    total.value = data["total"];
    loading.value = false;
  });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery(true);
}

/**
 * 打开机构弹窗
 *
 * @param parentId 父机构ID
 * @param ExamId 机构ID
 */
async function handleOpenDialog(parentId?: number, ExamId?: number) {
  const areaData = await AreaAPI.getList();
  areaOptions.province = [...areaData];
  dialog.visible = true;
  if (ExamId) {
    dialog.title = "修改报名";
    ExamAPI.getFormData(ExamId).then((data) => {
      Object.assign(formData, data);
      formData.area = [
        data["province_code"],
        data["city_code"],
        data["district_code"],
      ];
      formData.license = data["license"] ? [data["license"]] : [];
      formData.legalFace = data["legalFace"] ? [data["legalFace"]] : [];
      formData.legalBack = data["legalBack"] ? [data["legalBack"]] : [];
      formData.brand = data["brand"] ? [data["brand"]] : [];
      console.log(formData);
    });
  } else {
    dialog.title = "新增报名";
    formData.parent_id = parentOptions.value[0]["value"];
  }
}

/** 提交机构表单 */
function handleSubmit() {
  institutionFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const ExamId = formData.id;
      if (ExamId) {
        ExamAPI.update(ExamId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ExamAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;

  institutionFormRef.value.resetFields();
  institutionFormRef.value.clearValidate();

  formData.id = undefined;
  formData.parentId = 1;
  formData.status = 1;
  formData.sort = 1;
  formData.area = [];
  formData.license = [];
  formData.legalFace = [];
  formData.lagalBack = [];
  formData.brand = [];
}

function setArea($event) {
  console.log($event);
  formData.area = [$event.province, $event.city, $event.district];
}
function previewVideo(data: any) {
  ExamAPI.getVideo(data.id).then((res: any) => {
    if (res.video_url != null) {
      window.open(res.video_url, "_blank");
    } else if (res.video_local_url != null) {
      window.open(
        // "http://0.0.0.0:8000/" + res.video_local_url,
        "https://kj.cdfh2012.com/" + res.video_local_url,
        "_blank"
      );
    }
  });
}
function handleOpenUpload(answerId) {
  showUpload.value = true;
  console.log(answerId);
  answer_id.value = answerId;
}
function downloadVideo(data: any) {
  ExamAPI.getVideo(data["id"]).then((res: any) => {
    let videoUrl: string = "";
    if (res.video_url != null) {
      videoUrl = res.video_url;
    } else if (res.video_local_url != null) {
      videoUrl = "https://kj.cdfh2012.com/" + res.video_local_url;
    }
    const download =
      data.name +
      "_" +
      (data.type == 1 ? "朗诵" : "主持") +
      data.level +
      "级_" +
      "考试视频.mp4"; // 指定下载文件名
    fetch(videoUrl)
      .then((response) => response.blob())
      .then((blob) => {
        // 创建一个指向blob对象的URL
        const url = window.URL.createObjectURL(blob);
        // 创建下载链接
        const link = document.createElement("a");
        link.href = url;
        link.download = download; // 指定下载文件名
        document.body.appendChild(link);
        link.click(); // 触发下载
        document.body.removeChild(link); // 清除临时创建的链接
        window.URL.revokeObjectURL(url); // 释放blob对象URL
      })
      .catch((error) => console.error("下载视频失败:", error));
  });
}
onMounted?.(() => {
  handleQuery(true);
});
</script>
